package thread;

class MyBlockingQueue <T>{
    T[] data = null;

    //头节点
    public int head;
    //尾结点
    public int tail;
    //当前长度
    public int size;


    public  MyBlockingQueue(Integer capacity) {
        data = (T[]) new Object[capacity];
    }


    //插入数据
    public void put(T s){
        synchronized (this) {
            //满队列
            //使用while是为了确保wait被唤醒之后，再次确定if条件，是否能继续执行，防止被Interrupt等其他给唤醒而非通知唤醒
            while (size == data.length) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }

            data[tail] = s;
            tail++;
            if(tail >= data.length) {
                tail = 0;
            }
            size++;
            this.notify();
        }
    }

    //删除数据
    public T take() throws InterruptedException {
        //空队列
        T ret = null;
        synchronized (this) {
            while (size == 0) {
                this.wait();
            }

            ret = data[head];
            head++;
            if(head >= data.length) {
                head = 0;
            }
            size--;
            this.notify();
        }
        return  ret;
    }

}


public class Demo30 {
    public static void main(String[] args) {

    }
}
